package com.ss.webutil.wechat.pay;

import com.ss.webutil.net.HttpSSL;
import com.ss.webutil.struct.ResultModel;
import com.ss.webutil.util.XStreamEx;
import com.ss.webutil.wechat.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by LiYm on 2015/11/30.
 */
public class WXPayHelper {

    protected static final String PAY_PRE_FATAL = "预支付协议级错误";
    protected static final String PAY_PRE_NETWORK_ERROR = "网络错误，无法获取预支付ID";

    protected static Logger logger = LoggerFactory.getLogger(WXPayHelper.class);

    final static SimpleDateFormat wxFormat = new SimpleDateFormat("yyyyMMddHHmmss");

    public static ResultModel<PrepayResp> prepayRequest (String title, String detail, String outTradeNO,
                                                    int totalFee, String notifyURL, String openID,
                                                    Date startTime, Date endTime, Config config) {

        XStreamEx xStreamEx = new XStreamEx();
        PrepayReq req = new PrepayReq(config);
        req.setBody(title);
        req.setDetail(detail);
        req.setOut_trade_no(outTradeNO);
        req.setTotal_fee(totalFee);
        req.setSpbill_create_ip(config.getServerIP());
        req.setNotify_url(notifyURL);
        req.setTrade_type(BaseRequest.JSAPI);
        req.setOpenid(openID);
        req.setTime_start(wxFormat.format(startTime.getTime()));
        req.setTime_expire(wxFormat.format(endTime.getTime()));
        req.signature(config);
        xStreamEx.alias("xml", PrepayReq.class);
        String xml = xStreamEx.toXML(req);
        logger.info(xml);
        xml = HttpSSL.post("https://api.mch.weixin.qq.com/pay/unifiedorder", xml);
        if (xml == null) {
            return new ResultModel<>(PAY_PRE_NETWORK_ERROR);
        }
        logger.info(xml);

        xStreamEx.alias("xml", PrepayResp.class);
        PrepayResp resp = (PrepayResp)xStreamEx.fromXML(xml);
        if (!resp.getReturn_code().equals("SUCCESS")) {
            return new ResultModel<>(String.format("%s(%s)", PAY_PRE_FATAL, resp.getReturn_msg()));
        }

        if (!resp.getResult_code().equals("SUCCESS")) {
            return new ResultModel<>(String.format("%s(%s)",resp.getErr_code_des(), resp.getErr_code()));
        }

        return new ResultModel<>(resp);
    }

}
